package org.groupg.practice.configuration;

import org.apache.commons.configuration2.XMLConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.convert.DefaultListDelimiterHandler;
import org.apache.commons.configuration2.ex.ConfigurationException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class FullConfigLoader {
    public static void main(String[] args) {
        try {
            AppConfig config = loadConfig("app-config.xml");
            System.out.println(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static AppConfig loadConfig(String file) throws ConfigurationException {
        XMLConfiguration xmlConfig = new FileBasedConfigurationBuilder<>(XMLConfiguration.class)
                .configure(new Parameters().xml()
                        .setFileName(file)
                        .setSchemaValidation(true) // 启用 XSD 校验
                        .setListDelimiterHandler(new DefaultListDelimiterHandler(',')))
                .getConfiguration();

        AppConfig appConfig = new AppConfig();

        // 解析单一值
        appConfig.setName(xmlConfig.getString("app.name"));
        appConfig.setVersion(xmlConfig.getInt("app.version"));
        appConfig.setPrice(xmlConfig.getBigDecimal("app.price"));
        appConfig.setReleaseDate(parseDate(xmlConfig.getString("app.releaseDate")));

        // 解析简单列表
        appConfig.setModules(xmlConfig.getList(String.class, "app.modules.module"));
        appConfig.setPorts(xmlConfig.getList(Integer.class, "app.ports.port"));

        // 解析复杂对象列表
        List<User> users = new ArrayList<>();
        List<Object> userIds = xmlConfig.getList("app.users.user[@id]");
        for (Object idObj : userIds) {
//            xmlConfig.
            int index = userIds.indexOf(idObj);
            String baseKey = "app.users.user(" + index + ")";

            User user = new User();
            user.setId(xmlConfig.getInt(baseKey + "[@id]"));
            user.setUsername(xmlConfig.getString(baseKey + ".username"));
            user.setRoles(xmlConfig.getList(String.class, baseKey + ".roles.role"));
            users.add(user);
        }
        appConfig.setUsers(users);

        return appConfig;
    }

    private static LocalDate parseDate(String dateStr) {
        return LocalDate.parse(dateStr, DateTimeFormatter.ISO_DATE);
    }
}